//
//  SearchCacheViewController.m
//  B2C
//
//  Created by xiaowu on 2017/7/26.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "SearchCacheViewController.h"
#import "SearchLocalTool.h"
#import "SearchHotWordCell.h"
#import "SearchCacheCell.h"
#import "GoodsListFiltrateViewController.h"
#import "SearchTypeView.h"
#import <Masonry/Masonry.h>

@interface SearchCacheViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *cacheArr;
@property (nonatomic, strong) NSMutableArray *hotSearchArr;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) SearchHotWordCell *hotWordCell;

@property (nonatomic, strong) UIView *clearMaskView;
@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic,strong) SearchTypeView * searchTypeView;
@property (nonatomic,assign) NSInteger searchType; // 0：按照宝贝搜索， 1：按照店铺搜索
@end

@implementation SearchCacheViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _hotWordCell = [[SearchHotWordCell alloc] init];
        _cacheArr = [NSMutableArray array];
        _hotSearchArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self getCacheData];

    [self configureUI];
    [self loadHotSearchList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getCacheData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor NavBarColor]];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.clearMaskView.frame = CGRectMake(0, 0, self.view.width, self.view.height - self.clearMaskView.top);
}

#pragma mark - Network
- (void)loadHotSearchList {
    //MARK:测试
//    [self.hotSearchArr addObjectsFromArray:@[@"aaa",@"打发",@"asdfadf",@"发送到我",@"凄凄切切",@"人人人人若",@"哈哈哈哈",@"鞍山",@"看林俊杰哦",@"啊"]];
//    [self showHotSearchData];
    //MARK:--
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Hot_Search parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.hotSearchArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                NSString *str = [modelDic safeStringForKey:@"hsname"];
                [weakSelf.hotSearchArr addObject:str];
            }
            [weakSelf showHotSearchData];
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - Method

- (void)configureUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor whiteColor];
    // 导航栏搜索框
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(0, 0, ScreenWidth - 15 * 4 - 28 * 2, 28);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 28);
    self.navigationItem.titleView = self.searchView;
    
    self.searchTypeView = [[SearchTypeView alloc] init];
    __weak typeof(self) weakSelf = self;
    self.searchTypeView.didClickedBtnBlock = ^(NSInteger index) {
        //点击店铺或者宝贝
        NSLog(@"点击的索引是%ld",index);
        weakSelf.searchType = index;
    };
    [self.view addSubview:self.searchTypeView];
    self.searchTypeView.frame = CGRectMake(0,0, ScreenWidth, 40);
    
    UIView * blankView = [UIView new];
    blankView.backgroundColor = [UIColor colorWithHex:0xf0f3f5 alpha:1];
    [self.view addSubview:blankView];
    [blankView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.searchTypeView);
        make.top.equalTo(self.searchTypeView.mas_bottom);
        make.height.equalTo(@10);
    }];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView clearExtendCellLine];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    [self.view addSubview:self.clearMaskView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
    [self.clearMaskView addGestureRecognizer:tapGesture];
    


    [self.tableView registerNib:[UINib nibWithNibName:@"SearchCacheCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cacheCell"];
    
    [self responseBlock];
}

- (void)getCacheData {
    NSMutableArray *cache = [SearchLocalTool getSearchLocalCache];
    self.cacheArr = cache;
    
    [self.tableView reloadData];
}

- (void)showHotSearchData {
    [self.hotWordCell setTitlesArr:self.hotSearchArr];
    [self.tableView reloadData];
}

- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.hotWordCell.block = ^(NSInteger index) {
        NSString *str = [weakSelf.hotSearchArr safeObjectAtIndex:index];
        [weakSelf searchWithStr:str];
    };
}

- (void)searchWithStr:(NSString *)str {
    NSMutableArray *cache = [SearchLocalTool getSearchLocalCache];
    
    if ([cache containsObject:str]) {
        [cache removeObject:str];
    }
    [cache insertObject:str atIndex:0];
    [SearchLocalTool saveSearchLocalCache:cache];
    
//    self.searchBar.text = @"";
    
    if (self.type == SearchCacheViewControllerTypeForList) {
        if (self.block) {
            self.block(str);
        }
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        GoodsListFiltrateViewController *listVC = [[GoodsListFiltrateViewController alloc] init];
        listVC.keyword = str;
        listVC.searchType = self.searchType;
        [self.navigationController pushViewController:listVC animated:YES];
    }
}

#pragma Action
- (void)deleteCache:(UIButton *)sender {
    self.cacheArr = [NSMutableArray array];
    [SearchLocalTool saveSearchLocalCache:self.cacheArr];
    [self.tableView reloadData];
}

- (void)rightItemClick:(UIButton *)sender {
    [self viewEndEditing];
    if (self.searchBar.text.length > 0) {
        [self searchWithStr:self.searchBar.text];
    } else {
        [self.searchBar becomeFirstResponder];
    }
}

- (void)viewEndEditing {
    [self.searchBar resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    self.clearMaskView.hidden = NO;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    self.clearMaskView.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.cacheArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.hotWordCell;
    } else {
        SearchCacheCell *cacheCell = [tableView dequeueReusableCellWithIdentifier:@"cacheCell" forIndexPath:indexPath];
        cacheCell.titleLabel.text = [self.cacheArr safeObjectAtIndex:indexPath.row];
        return cacheCell;
    }
    return [[UITableViewCell alloc] init];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [SearchHotWordCell getHeightWithArr:self.hotSearchArr];
    }
    return 56;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] init];
    label.font = TextPingFangFontSize(14);
    label.textColor = [UIColor blackTextColor];
    label.frame = CGRectMake(15, 0, 100, 40);
    
    UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
    delete.frame = CGRectMake(tableView.width - 15 - 40, 0, 40, 40);
    [delete setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
//    [delete setTitle:@"delete" forState:UIControlStateNormal];
    [delete addTarget:self action:@selector(deleteCache:) forControlEvents:UIControlEventTouchUpInside];
    
    
    if (section == 0) {
        label.text = @"热门搜索";
    } else if (section == 1) {
        label.text = @"历史搜索";
        [view addSubview:delete];
    }
    
    [view addSubview:label];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, view.height - 0.5, ScreenWidth - 30, 0.5)];
    lineView.backgroundColor = [UIColor grayBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        [self searchWithStr:[self.cacheArr safeObjectAtIndex:indexPath.row]];
    }
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self viewEndEditing];
    [self searchWithStr:searchBar.text];
}

#pragma mark - Getters
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:14];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor colorWithHex:0xF5F5F5  alpha:1.0]];
    }
    return _searchView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //        [_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        searchField.backgroundColor = [UIColor colorWithHex:0xF5F5F5  alpha:1.0];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
        searchField.font = TextPingFangFontSize(14);

    }
    return _searchBar;
}

- (UIView *)clearMaskView {
    if (!_clearMaskView) {
        _clearMaskView = [[UIView alloc] init];
        _clearMaskView.backgroundColor = [UIColor clearColor];
        _clearMaskView.hidden = YES;
    }
    return _clearMaskView;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setTitle:@"搜索" forState:UIControlStateNormal];
        _rightButton.titleLabel.font = TextPingFangFontSize(14);
        [_rightButton setTitleColor:[UIColor gray66Color] forState:UIControlStateNormal];
        [_rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        
        _rightButton.size = CGSizeMake(39, 30);
        _rightButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
//        _rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, 32, 0, -10);
        [_rightButton addTarget:self action:@selector(rightItemClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _rightButton;
}

@end
